package com.zhongli.devplatform.security.handler;

import com.alibaba.fastjson.JSON;
import com.zhongli.devplatform.po.sys.ReadUserLoginPO;
import com.zhongli.devplatform.bean.Res;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

//    @Autowired
//    private IUserLoginService userLoginService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {


        ReadUserLoginPO readUserLoginPO = new ReadUserLoginPO();


        Res res = null;
        if (e instanceof InternalAuthenticationServiceException) {
            res = Res.error("用户名或密码不能为空");
        } else if (e instanceof UsernameNotFoundException) {
            res = Res.error("用户名不存在");
        } else if (e instanceof BadCredentialsException) {
            res = Res.error("用户名或密码错误");
        } else if (e instanceof DisabledException) {
            res = Res.error("你的账户已被禁用，请联系管理员");
        } else if (e instanceof AccountExpiredException) {
            res = Res.error("你的账户已过期，请联系管理员");
        } else if (e instanceof LockedException) {
            res = Res.error("你的账户已被锁定，请联系管理员");
        } else {
            res = Res.error("登录出现未知错误，请联系管理员");
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(res));
        out.flush();
        out.close();
//
//        UserAgent userAgent = UserAgent.parseUserAgentString(httpServletRequest.getHeader("User-Agent"));
//        userLoginPO.setLoginBrowser(userAgent.getBrowser().getName());
//        userLoginPO.setLoginIp(CusAccessObjectUtil.getIpAddress(httpServletRequest));
//        userLoginPO.setLoginRemark(res.getMsg());
//        userLoginPO.setLoginStatus("0");
//        userLoginPO.setLoginType("1");
//        userLoginPO.setLoginUa(httpServletRequest.getHeader("User-Agent"));
//        userLoginPO.setLoginTime(new Date());
//        userLoginPO.setUserName(httpServletRequest.getParameter("username"));
//        userLoginService.save(userLoginPO);

    }
}
